import 'package:flame/components.dart';

import '../../../component/SpriteEntity.dart';

// 影子
class BodyShadow extends SpriteEntity {
  final Vector2 bodySize; // 阴影大小
  final Vector2 bodyPosition; // 初始位置
  final PositionComponent? target; // 跟随物体
  double _aspectRadio = 1.0; // 阴影宽高比

  // 默认阴影
  BodyShadow(
    super.spriteImg, {
    required this.bodySize,
    required this.bodyPosition,
  }) : target = null;

  // 跟踪阴影
  BodyShadow.following(
    super.spriteImg, {
    required PositionComponent targetEntity,
  })  : bodySize = Vector2.zero(),
        bodyPosition = Vector2.zero(),
        target = targetEntity;

  @override
  Future<void> onLoad() async {
    priority = shadowPriority;
    await super.onLoad();
    if (target == null && sprite != null) {
      _aspectRadio = sprite!.image.width / sprite!.image.height;
      final shadowHeight = bodySize.x / _aspectRadio;
      position = Vector2(
        bodyPosition.x,
        bodyPosition.y + bodySize.y - shadowHeight,
      );
      size = Vector2(bodySize.x, shadowHeight);
    }
  }

  @override
  void update(double dt) {
    super.update(dt);
    if (target != null && sprite != null) {
      final radio = sprite!.image.width / sprite!.image.height;
      if (radio < 1) {
        final shadowHeight = target!.size.x / radio;
        position = Vector2(
          target!.x,
          target!.y - shadowHeight / 2 + target!.size.y,
        );
        size = Vector2(target!.size.x, shadowHeight);
      } else {
        final shadowHeight = target!.size.x / radio * 0.25;
        position = Vector2(
          target!.x,
          target!.y - shadowHeight / 2 + target!.size.y,
        );
        size = Vector2(target!.size.x, shadowHeight);
      }
    }
  }
}
